package com.eliza.workmanager

import android.os.Build
import android.os.Bundle
import android.util.Log
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import androidx.work.*
import com.eliza.workmanager.tools.Tools
import com.eliza.workmanager.work.AWork
import java.time.Duration
import java.util.concurrent.TimeUnit


class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

    }

    fun mAddWork(view: View) {
        aWork()

    }

    fun aWork() {
        val wm = WorkManager.getInstance(this)
        val inputData: Data = Data.Builder()
            .putString("input_data", "jack")
            .build()
        val work = setWork(setConstraints(), inputData)
        Tools.LogToast(this, "== work:  ${work?.id}==")

        work?.let {
            Log.d(this::class.java.name, "WorkManager::")

            wm.enqueue(it)//添加到 任务列表
            wm.getWorkInfoByIdLiveData(work.id).observe(this) { workInfo ->
                Log.i(this::class.java.name, "getWorkInfoByIdLiveData::${workInfo.toString()}");
            }
        }


    }

    /**
     * 设置触发条件
     * */
    private fun setConstraints(): Constraints {
        /*
    NetworkType.NOT_REQUIRED：对网络没有要求
    NetworkType.CONNECTED：网络连接的时候执行
    NetworkType.UNMETERED：不计费的网络比如WIFI下执行
    NetworkType.NOT_ROAMING：非漫游网络状态
    NetworkType.METERED：计费网络比如3G，4G下执行。
* */
        val constraints =
            Constraints.Builder() // .setRequiredNetworkType(NetworkType.CONNECTED)//网络连接时执行
                // .setRequiresBatteryNotLow(true) //不在电量不足执行
                // .setRequiresCharging(true) //在充电时执行
                // .setRequiresStorageNotLow(true) //不在存储容量不足时执行
                // .setRequiresDeviceIdle(true) //在待机状态下执行 调用需要API级别最低为23

                //注意：不代表恢复网络了，就立马执行
                .setRequiredNetworkType(NetworkType.NOT_REQUIRED)
                .build()
        Tools.LogToast(this, "==== constraints is set ====")

        return constraints
    }

    /**
     * 设置work
     * */
    private fun setWork(constraints: Constraints, inputData: Data): OneTimeWorkRequest? {
        //        设置任务 false
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            return OneTimeWorkRequest.Builder(AWork::class.java)
                //设置触发条件
                .setConstraints(constraints)
                //设置延迟执行
                .setInitialDelay(5, TimeUnit.SECONDS)
                //指数退避策略
                .setBackoffCriteria(BackoffPolicy.LINEAR, Duration.ofSeconds(2))
                //设置tag标签
                .addTag("workRequest1")
                //参数传递
                .setInputData(inputData)
                .build();
        }
        Log.e(this::class.java.name, "==== OneTimeWorkRequest is null ====")
        Tools.LogToast(this, "==== OneTimeWorkRequest is null ====")

        Log.e(this::class.java.name, "==== ${Build.VERSION.SDK_INT >= Build.VERSION_CODES.O} ====")

        return null
    }

    private fun setWork2(constraints: Constraints, inputData: Data): PeriodicWorkRequest? {
        //        设置任务
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            //周期性任务      //不能少于15分钟
            return PeriodicWorkRequest.Builder(AWork::class.java, Duration.ofMinutes(15))
                .build()
        }
        Log.e(this::class.java.name, "==== PeriodicWorkRequest is null ====")
        return null
    }

}